package com.sky.aspect;


import com.sky.annotation.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    @Pointcut("execution(* com.sky.mapper.*.*(..) )&&@annotation(com.sky.annotation.AutoFill)")
    public void autoFillPointcut(){
    }

    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint){
        log.info("开始进行自动填充......");
        // 获取参数
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();// 获取方法签名
        AutoFill autoFill = methodSignature.getMethod().getAnnotation(AutoFill.class);// 获取注解
        OperationType operationType = autoFill.value();// 获取数据库操作类型
        // 获取当前被拦截方法参数的值
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0){
            return;
        }
        Object entry  = args[0];
        //准备赋值数据
        LocalDateTime now = LocalDateTime.now();
        Long currentId = BaseContext.getCurrentId();
        if (operationType.equals(OperationType.INSERT)){
            //为四个公共字段都赋值
            try {
                Method setCreateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
                Method setCreateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);

                setCreateTime.invoke(entry, now);
                setCreateUser.invoke(entry, currentId);
                setUpdateTime.invoke(entry, now);
                setUpdateUser.invoke(entry, currentId);

            } catch (Exception e) {
                e.printStackTrace();
            }

        }else if (operationType.equals(OperationType.UPDATE)){
            //为两个公共字段都赋值
            try {
                Method setUpdateTime = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
                Method setUpdateUser = entry.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
                setUpdateTime.invoke(entry, now);
                setUpdateUser.invoke(entry, currentId);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
